package com.fly.api.aop;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 
 * aop实现代码运行时间日志打印
 * 
 * @author 00fly
 * @version [版本号, 2018年7月2日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Aspect
@Component
public class RunTimeAspect
{
    private static final Logger LOGGER = LoggerFactory.getLogger(RunTimeAspect.class);
    
    /**
     * 定义连接点
     * 
     * @param joinPoint
     * @see [类、类#方法、类#成员]
     */
    @Around("within(com.fly.api..*)")
    public Object around(ProceedingJoinPoint joinPoint)
        throws Throwable
    {
        String className = joinPoint.getTarget().getClass().getSimpleName();
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        Method method = signature.getMethod();
        String methodName = new StringBuffer(className).append(".").append(method.getName()).toString();
        boolean isController = method.isAnnotationPresent(RequestMapping.class);
        Object result = null;
        if (isController)
        {
            HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
            StringBuilder url = new StringBuilder(request.getRequestURI());
            String query = StringUtils.trimToEmpty(request.getQueryString());
            if (StringUtils.isNotBlank(query))
            {
                url.append("?");
            }
            LOGGER.info("start running method = {}, url = {}{}", methodName, url, query);
        }
        StopWatch clock = new StopWatch();
        clock.start(methodName);
        result = joinPoint.proceed();
        clock.stop();
        if (isController)
        {
            LOGGER.info("end in {} ms, method = {}\n", clock.getTotalTimeMillis(), clock.getLastTaskName());
        }
        else
        {
            LOGGER.info("running {} ms, method = {}", clock.getTotalTimeMillis(), clock.getLastTaskName());
        }
        return result;
    }
}
